package com.konsung.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.konsung.bean.CheckData;
import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.bean.RecordAllMeasureResult;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.MeasureDataBeanDao;
import com.konsung.healthfile.R;
import com.konsung.kslibrary.base.BaseActivity;
import com.konsung.kslibrary.base.MvpView;
import com.konsung.network.UploadData;
import com.konsung.presenter.HealthReportPresenter;
import com.konsung.presenter.impl.HealthReportPresenterImpl;
import com.konsung.provide.ProviderReader;
import com.konsung.ui.adapter.SpinnerAdapter;
import com.konsung.ui.defineview.EcgReportDrawable;
import com.konsung.ui.defineview.PhysicalExaminationDrawable;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.ClickUtils;
import com.konsung.util.IdCardUtil;
import com.konsung.util.KParamType;
import com.konsung.util.PrintUtil;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;

import org.greenrobot.greendao.query.LazyList;
import org.greenrobot.greendao.query.WhereCondition;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.co.senab.photoview.PhotoView;

/**
 * 修改居民档案信息的弹窗
 */
public class HealthReportActivity extends BaseActivity<HealthReportPresenterImpl> implements
        HealthReportPresenter.View, MvpView {

    @BindView(R.id.sp_measure_time)
    Spinner spMeasureTime;
    @BindView(R.id.tv_how_mach)
    TextView tvHowMach;
    @BindView(R.id.btn_check_ecg)
    Button btnCheckEcg;
    @BindView(R.id.btn_print_report)
    Button btnPrintReport;
    @BindView(R.id.iv_report)
    ImageView ivReport;
    @BindView(R.id.btn_upload)
    Button btUpload;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private PhysicalExaminationDrawable drawable;
    private List<MeasureDataBean> measureDataBeen;
    private PatientBean patientBean;
    private PrintUtil printUtil;

    private MeasureDataBean currentMeasureData;
    private boolean isClickUpload = false; //标识是否点击过报告上传

    private RecordAllMeasureResult printResult; //动态打印显示的依据类

    public static UsbDevice usbDevice = null; //全局保存第一次获取的有效的打印机UsbDevice对象
    /**
     * 获取打印机连接的广播接收者
     */
    private BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (("android.hardware.usb.action.USB_DEVICE_DETACHED").equals(
                    intent.getAction())) {
                // 当有usb 拔出的时候检测一次，奔图打印机是否被拔出
                if (printUtil.getPrinting()) {
                    if (!printUtil.checkPrintUSB(context)) {
                        printUtil.cancelSendDataToServer(); //停止打印

                        printUtil.checkUSB(3); //传入打印机未连接的参数，提示用户

                        //打印机USB拔出去后判断条件还原
                        usbDevice = null;
                    }
                }
            }
            if (("android.hardware.usb.action.USB_DEVICE_ATTACHED").equals(
                    intent.getAction())) {
                // 当有usb 插入的时候检测一次是否存在打印机
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_report);
        ButterKnife.bind(this);
        bindEvent();
        initData();
        initRecerver();
        initMeasureTime();
        spMeasureTime.setPopupBackgroundDrawable(UiUtils.getDrawable(R.drawable.bg_drop_down_box));
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BroadcastUtils.sendHideForStartManage();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        tvTitle.setText(R.string.physical_examination_report);
        patientBean = presenter.getCurrentPatient();
        measureDataBeen = presenter.getAllMeasureData(getIntent()
                .getStringExtra(ReportListActivity.MEASURE_UUID));
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        drawable = new PhysicalExaminationDrawable(this, new MeasureDataBean(),
                patientBean, width, height);
        currentMeasureData = measureDataBeen.get(0);
        printUtil = new PrintUtil(this, currentMeasureData, patientBean);
        //测量数据没上传时，上传按钮才可以点击
        if (measureDataBeen.size() > 0) {
            if (isNotUpload(measureDataBeen)) {
                btUpload.setEnabled(true);
            }
        }
        printResult = presenter.getPrintResult(currentMeasureData);
    }

    /**
     *  检查健康档案是否有未上传的
     * @param measureDataBeen  a
     * @return a
     */
    private boolean isNotUpload(List<MeasureDataBean> measureDataBeen) {
        for (int i = 0; i < measureDataBeen.size(); i++) {
            if (!measureDataBeen.get(i).getUploadFlag()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 当连接奔图打印机的时候开启USB的拔插监听
     */
    public void initRecerver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(usbReceiver, filter);
    }

    /**
     * 初始化测量时间列表
     */
    private void initMeasureTime() {
        SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState.LONG);
        tvHowMach.setText(" " + String.valueOf(measureDataBeen.size()) + " ");
        String[] timeArr = new String[measureDataBeen.size()];
        for (int i = 0; i < measureDataBeen.size(); i++) {
            timeArr[i] = dateFormat.format(new Date(measureDataBeen.get(i).getMeasureTime()))
                    + getUpdateFlag(measureDataBeen.get(i).getUploadFlag());
        }
        SpinnerAdapter adapter = new SpinnerAdapter(this, timeArr);
        spMeasureTime.setAdapter(adapter);
    }

    /**
     * 初始化视图数据
     */
    private void initView() {
        initMeasureData();
        btnCheckEcg.setEnabled(currentMeasureData.getEcgIsMeasure());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4) { //F1
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 绑定点击事件
     */
    private void bindEvent() {
        ivBack.setOnClickListener(this);
        btnCheckEcg.setOnClickListener(this);
        btnPrintReport.setOnClickListener(this);
        spMeasureTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentMeasureData = measureDataBeen.get(position);
                initView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //点击上传未上传的测量数据
        btUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ClickUtils.isFastClickTwo()) {
                    return;
                }
                if (UiUtils.isConnectNetWork(MyApplication.getContext())) {
                    UiUtils.postLongThread(new Runnable() {
                        @Override
                        public void run() {
                            CheckData checkData = ProviderReader.getCheckData(HealthReportActivity
                                    .this);
                            if (checkData == null) {
                                ToastUtils.showShortToastSafe(getString(R.string
                                        .user_not_upload));
                                return;
                            }
                            isClickUpload = true;
                            UiUtils.showProgress(MyApplication.getContext(), getString(R.string
                                    .now_upload));
                            MeasureDataBeanDao measureDataDao = GreenDaoManager
                                    .getMeasureDao(HealthReportActivity.this);
                            UploadData uploadData = new UploadData(HealthReportActivity.this);
                            WhereCondition where1 = MeasureDataBeanDao.Properties.Idcard
                                    .eq(patientBean.getIdcard());
                            WhereCondition where2 = MeasureDataBeanDao.Properties.UploadFlag
                                    .eq(false);

                            LazyList<MeasureDataBean> query = measureDataDao.queryBuilder()
                                    .where(where1)
                                    .where(where2)
                                    .listLazy();
                            for (int i = 0; i < query.size(); i++) {
                                boolean isFile = uploadData.uploadMeasureDataMore(query.get(i),
                                        patientBean, checkData, true);
                                //查询到没有健康档案就不进行上传了
                                if (!isFile) {
                                    ToastUtils.showShortToastSafe(getString(R
                                            .string.no_file_please_upload));
                                    break;
                                }
                            }
                            //上传成功后，按钮置灰
                            LazyList<MeasureDataBean> measureDataBean = measureDataDao
                                    .queryBuilder()
                                    .where(where1)
                                    .where(where2)
                                    .listLazy();
                            if (measureDataBean.size() <= 0) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        btUpload.setEnabled(false);
                                    }
                                });
                            }
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            UiUtils.hideProgress();
                            //上传后重新刷新体检列表
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    initMeasureTime();
                                }
                            });
                        }
                    });
                } else {
                    ToastUtils.showShortToastSafe(R.string.no_net);
                }
            }
        });
    }

    /**
     * 初始化测量数据
     */
    private void initMeasureData() {
        //赋值医生姓名
        CheckData checkData = ProviderReader.getCheckData(this);
        if (checkData != null && checkData.getCheckData() != null) {
            String empName = checkData.getCheckData().getEmpName();
            currentMeasureData.setDoctor(empName);
        }
        drawable.setData(currentMeasureData, patientBean);
        drawable.draw(new Canvas()); //先计算出Y轴高度
        int y = drawable.getY() + 100; //100为底部空隙  1280为图片宽度
        Bitmap bitmap = Bitmap.createBitmap(1280, y, drawable.getOpacity() != PixelFormat.OPAQUE ?
                Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);

        drawable.setBounds(0, 0, 1280, y);
        drawable.draw(canvas);
        ivReport.setMaxHeight(y);
        ivReport.setMaxWidth(1280);
        ivReport.setImageBitmap(bitmap);
    }

    @Override
    public void alterResult(AlterPatientActivity.AlterState state) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_check_ecg:
                final WindowManager.LayoutParams params = new WindowManager.
                        LayoutParams(WindowManager.LayoutParams.TYPE_PHONE);
                params.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; //可以获取back事件
                LayoutInflater flater = (LayoutInflater) UiUtils.getContent().
                        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View ecgView = flater.inflate(R.layout.pop_ecg_report, null);
                ReportView reportView = new ReportView();
                ButterKnife.bind(reportView, ecgView);
                initReportPatientData(reportView);
                initReportMeasureData(reportView);
                initReportEcgWave(reportView);
                final WindowManager windowManager = getWindowManager();
                windowManager.addView(ecgView, params);
                reportView.llReortView.setOnKeyListener(new View.OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                                windowManager.removeView(ecgView);
                                return true;
                            default:
                                return false;
                        }
                    }
                });
                reportView.btnStopReport.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        windowManager.removeView(ecgView);
                    }
                });
                break;
            case R.id.btn_print_report:
                printUtil.setMeasureBean(currentMeasureData);
                printUtil.setRecordAllPrintResult(printResult);
                printUtil.startPrint();
                break;
            default:
                break;
        }
    }

    /**
     * 获取测量数据是否上穿
     * @param uploadFlag 上传状态
     * @return 上传状态
     */
    private String getUpdateFlag(boolean uploadFlag) {

        return uploadFlag ? UiUtils.getString(R.string.have_already_uploaded)
                : UiUtils.getString(R.string.haven_uploaded);
    }

    /**
     * 初始化病人信息
     * @param holder 体检报告控件容器
     */
    private void initReportPatientData(ReportView holder) {
        if (patientBean != null) {
            holder.tvReportAge.setText(String.valueOf(patientBean.getAge()));
            holder.tvReportName.setText(patientBean.getName());
            holder.tvReportIdcard.setText(patientBean.getIdcard());
            SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState.LONG);
            String measureTime = dateFormat.format(new Date(currentMeasureData.getMeasureTime()));
            holder.tvReportMeasureTime.setText(UiUtils.getString(R.string.measure_time_colon) + " "
                    + measureTime);
            holder.tvReportSex.setText(IdCardUtil.getSexFormDB(patientBean.getSex()));
        }
    }

    /**
     * 初始化测量数据
     * @param holder 体检报告控件容器
     */
    private void initReportMeasureData(ReportView holder) {
        if (currentMeasureData != null) {
            String divide = UiUtils.getString(R.string.unit_divide);
            String ms = UiUtils.getString(R.string.unit_ms);
            String limit = UiUtils.getString(R.string.unit_limit);
            String mv = UiUtils.getString(R.string.unit_mv);
            String qtQtc = currentMeasureData.getQt() + divide + currentMeasureData.getQtc() + ms;
            String pQrsT = currentMeasureData.getPAxis() + divide + currentMeasureData.getQrsAxis()
                    + divide + currentMeasureData.getTAxis() + limit;
            holder.tvReportHr.setText(currentMeasureData.getTrendValue(KParamType.ECG_HR)
                    / GlobalConstant.INT_FACTOR + UiUtils.getString(R.string.health_unit_bpm));
            holder.tvReportPr.setText(currentMeasureData.getPr() + ms);
            holder.tvReportQrs.setText(currentMeasureData.getQrs()
                    + UiUtils.getString(R.string.unit_ms));
            holder.tvReportQtqtc.setText(qtQtc);
            holder.tvReportPQrsT.setText(pQrsT);
            //协议上的单位是0.01mv。
            float rv5 = (float) currentMeasureData.getRv5() / GlobalConstant.FACTOR;
            float sv1 = (float) currentMeasureData.getSv1() / GlobalConstant.FACTOR;
            String rv5Sv1 = String.format(Locale.ENGLISH, "%.2f", rv5) + divide
                    + String.format(Locale.ENGLISH, "%.2f", sv1) + mv;
            holder.tvReportRv5Sv1.setText(rv5Sv1);
            holder.tvReportRv5Sv1Add.setText(String.format(Locale.ENGLISH, "%.2f", rv5 + sv1) + mv);
            holder.tvReportResult.setText(currentMeasureData.getEcgDiagnoseResult());
        }
    }

    /**
     * 初始化心电波形
     * @param holder 体检报告控件容器
     */
    private void initReportEcgWave(ReportView holder) {
        //获取全屏的宽高
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        final int width = displayMetrics.widthPixels;
        final int height = displayMetrics.heightPixels;
        EcgReportDrawable drawable = new EcgReportDrawable(currentMeasureData, height, width);
        // 1280屏幕宽度，575控件高度
        Bitmap bitmap = Bitmap.createBitmap(1280, 575, drawable.getOpacity() != PixelFormat.OPAQUE ?
                Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, 1280, 575);
        drawable.draw(canvas);
        holder.imgReport.setImageBitmap(bitmap);
    }

    /**
     * 获取打印结果显示
     * @return 打印结果类
     */
    public RecordAllMeasureResult getPrintResult() {
        return printResult;
    }

    @Override
    public HealthReportPresenterImpl initPresenter() {
        return new HealthReportPresenterImpl();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbReceiver);
        UiUtils.setMeasureDataBeen(null);
        if (isClickUpload) {
            //如果点击了数据上传则返回首页列表数据通过广播接受消息后更新列表数据信息
            BroadcastUtils.sendAddPatientSuccess();
            //发送广播刷新体检报告列表页当前页数据
            BroadcastUtils.sendRefreshMeasures();
        }
    }

    /**
     * 体检报告控件容器
     */
    public class ReportView {

        @BindView(R.id.ll_report_view)
        LinearLayout llReortView;
        @BindView(R.id.tv_report_name)
        TextView tvReportName;
        @BindView(R.id.tv_report_sex)
        TextView tvReportSex;
        @BindView(R.id.tv_report_age)
        TextView tvReportAge;
        @BindView(R.id.tv_report_idcard)
        TextView tvReportIdcard;
        @BindView(R.id.tv_report_measure_time)
        TextView tvReportMeasureTime;
        @BindView(R.id.btn_stop_report)
        Button btnStopReport;
        @BindView(R.id.tv_report_hr)
        TextView tvReportHr;
        @BindView(R.id.tv_report_pr)
        TextView tvReportPr;
        @BindView(R.id.tv_report_qrs)
        TextView tvReportQrs;
        @BindView(R.id.tv_report_qtqtc)
        TextView tvReportQtqtc;
        @BindView(R.id.tv_report_pQrsT)
        TextView tvReportPQrsT;
        @BindView(R.id.tv_report_rv5Sv1)
        TextView tvReportRv5Sv1;
        @BindView(R.id.tv_report_RV5SV1Add)
        TextView tvReportRv5Sv1Add;
        @BindView(R.id.tv_report_result)
        TextView tvReportResult;
        @BindView(R.id.img_report)
        PhotoView imgReport;
    }

    /**
     * 报告数据获取情况
     */
    public enum ReportState {
        SHOW_DATA,
        //显示数据
        EMPTY_MEASURE,
        //没有测量数据
        EMPTY_PATIENT, //没有设置居民
    }
}
